package com.begye.smartloan.apptest.renzheng.views

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.FillItemDoingHeaderBinding
import com.begye.smartloan.apptest.ext.addColor

class FillItemDoingHeader : LinearLayout {

    private var _binding: FillItemDoingHeaderBinding? = null
    private val binding get() = _binding!!

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        context?.let {
            val layout = View.inflate(it, R.layout.fill_item_doing_header, this)
            _binding = FillItemDoingHeaderBinding.bind(layout)
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        // Ensure binding is not null after inflation
        if (_binding == null) {
            throw IllegalStateException("ViewBinding not initialized for ${javaClass.simpleName}")
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null  // Clear the binding reference
    }

    fun addTag(value: String): FillItemDoingHeader {
        this.tag = value

        if (value.contains("personal_info", true)) {
            binding.fillItemHeaderIcon.setImageResource(R.drawable.dres_47)

        } else if (value.contains("work_info", true)) {
            binding.fillItemHeaderIcon.setImageResource(R.drawable.dres_49)

        } else if (value.contains("contact_info", true)) {
            binding.fillItemHeaderIcon.setImageResource(R.drawable.dres_48)

        } else if (value.contains("account_info", true)) {
            binding.fillItemHeaderIcon.setImageResource(R.drawable.dres_50)

        } else {
            binding.fillItemHeaderIcon.setImageResource(R.drawable.dres_50)
        }
        return this
    }

    fun addTitle(value: String): FillItemDoingHeader {
        binding.fillItemHeaderTitle.text = value
        binding.fillItemHeaderTitle.addColor("*", "#F55555")
        return this
    }

    fun hideContent(value: Boolean = true): FillItemDoingHeader {
        if (value) {
            binding.fillItemHeaderContent.visibility = View.GONE
        } else {
            binding.fillItemHeaderContent.visibility = View.VISIBLE
        }
        return this
    }

}